# Copyright (c) 2012-4 Aaron Sun <hisycg@gmail.com>. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.

#!/usr/bin/perl
use warnings;
use strict;
use IO::Socket;
use Data::Dumper;

my $opt;
my $socket;  #each client only have one socket.

sub init_opt{
  $opt->{name} = $ARGV[0] || $ENV{USER} || 'Anonymous';
  my $hostname = `hostname`;chomp($hostname);
  $opt->{host} = $hostname;
  $opt->{serv} = 'localhost';
  $opt->{port} = 55555;
}

sub init_connection{
  # create the socket
  $socket = IO::Socket::INET->new(
        PeerAddr => $opt->{serv},
        PeerPort => $opt->{port},
        Proto    => 'tcp',
        );
  defined $socket or die "ERROR: Can't connect to port $opt->{port} on $opt->{serv}: $!\n";
  print "Connected to server ...\n";
  print $socket "#CLIENTINFO#USER:$opt->{name},HOST:$opt->{host}\n";
#   print "USER:$opt->{name},HOST:$opt->{host}"."\n";
}

sub start_chat{
  my $recv_pid;
  my $line;
  die "can't fork: $!" unless defined($recv_pid=fork());
  if($recv_pid){
    while(defined($line=<$socket>)){
      print STDOUT $line;
#       print "\n-> ";
    }
    kill ("TERM",$recv_pid);
  }
  else{
    while(defined($line=<STDIN>)){
  #     print $socket "$name says: $line";
      print "\033[F";
      print $socket $line;
    }
  }
}

sub main{
  init_opt;
#   print Dumper($opt);
  init_connection;
  start_chat;
}

&main;